package idv.kikka.client;

import cn.hutool.core.date.DateUtil;
import idv.kikka.common.config.CommonConfig;
import idv.kikka.common.message.*;

import idv.kikka.common.protocol.MessageCodecSharable;
import idv.kikka.common.protocol.ProcotolFrameDecoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;

@Slf4j
public class ChatClient {
    public static void main(String[] args) {
        System.out.println("连接服务器中，请耐心等待...");
        NioEventLoopGroup group = new NioEventLoopGroup();
        LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.DEBUG);
        MessageCodecSharable MESSAGE_CODEC = new MessageCodecSharable();
        //线程间通信用
        CountDownLatch WAIT_FOR_LOGIN = new CountDownLatch(1);//倒计时锁，线程使用await()之后，等计数到0(其他线程用countDown直到0)，线程才会继续运行
        AtomicBoolean LOGIN=new AtomicBoolean(false);//登录是否成功，默认值为不成功
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.group(group);
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new ProcotolFrameDecoder());
//                    ch.pipeline().addLast(LOGGING_HANDLER);
                    ch.pipeline().addLast(MESSAGE_CODEC);
                    // 用来判断是不是 读空闲时间过长，或 写空闲时间过长
                    // 5min 内如果没有向服务器写数据，会触发一个 IdleState#WRITER_IDLE(写空闲) 事件
                    ch.pipeline().addLast(new IdleStateHandler(0, 5*60, 0));
                    // ChannelDuplexHandler 可以同时作为入站和出站处理器
                    ch.pipeline().addLast(new ChannelDuplexHandler() {
                        // 用来响应特殊事件
                        @Override
                        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception{
                            if(evt instanceof IdleStateEvent){
                                IdleStateEvent event = (IdleStateEvent) evt;
                                // 触发了写空闲事件
                                if (event.state() == IdleState.WRITER_IDLE) {
//                                    log.debug("3s 没有写数据了，向服务端发送一个心跳包");
                                    ctx.writeAndFlush(new PingMessage());
                                }
                            }
                        }
                    });
                    ch.pipeline().addLast("client handler",new ChannelInboundHandlerAdapter(){
                        //在连接建立后触发active事件
                        @Override
                        public void channelActive(ChannelHandlerContext ctx) throws Exception {
                            //负责接收用户在控制台的输入，负责向服务器发送消息
                            new Thread(()->{
                                Scanner scanner=new Scanner(System.in);
                                System.out.println("请输入用户名:");
                                String username = scanner.nextLine();
                                System.out.println("请输入密码:");
                                String password = scanner.nextLine();
                                //构造消息对象
                                LoginRequestMessage loginRequestMessage = new LoginRequestMessage(username, password);
                                //发送消息
                                ctx.writeAndFlush(loginRequestMessage);
                                System.out.println("等待后续操作...");
                                try {
                                    WAIT_FOR_LOGIN.await();//等待另一个线程使用countDown，计数减到0就继续运行
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                                if (!LOGIN.get()) {
                                    //如果登录失败
                                    ctx.channel().close();//关闭channel
                                    return;//关闭线程
                                }
                                //登录成功后，选择功能(空格间隔功能的选项)
                                System.out.println("==================================");
                                System.out.println("send [username] [content]");
                                System.out.println("gsend [group name] [content]");
                                System.out.println("gcreate [group name] [m1,m2,m3...]");
                                System.out.println("gmembers [group name]");
                                System.out.println("gjoin [group name]");
                                System.out.println("gquit [group name]");
                                System.out.println("quit");
                                System.out.println("==================================");
                                while (true){
                                    String command = scanner.nextLine();//输入所需功能
                                    String[] s = command.split(" ");
                                    switch (s[0]){
                                        case "send"://发送消息
                                            ctx.writeAndFlush(new ChatRequestMessage(username, s[1], s[2]));
                                            break;
                                        case "gsend"://群聊发送消息
                                            ctx.writeAndFlush(new GroupChatRequestMessage(username,s[1],s[2]));
                                            break;
                                        case "gcreate"://建立群聊
                                            Set<String> members=new HashSet<>(Arrays.asList(s[2].split(",")));
                                            members.add(username);//把自己加进去
                                            ctx.writeAndFlush(new GroupCreateRequestMessage(s[1],members));
                                            break;
                                        case "gmembers"://查看群聊内成员
                                            ctx.writeAndFlush(new GroupMembersRequestMessage(s[1]));
                                            break;
                                        case "gjoin"://加入群聊
                                            ctx.writeAndFlush(new GroupJoinRequestMessage(username,s[1]));
                                            break;
                                        case "gquit"://退出群聊
                                            ctx.writeAndFlush(new GroupQuitRequestMessage(username,s[1]));
                                            break;
                                        case "quit"://退出整个客户端
                                            ctx.channel().close();//关闭channel
                                            return;
                                    }
                                }
                            },"system in").start();
                        }
                        //接收响应消息
                        @Override
                        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//                            log.debug("msg: {}",msg);
                            if (msg instanceof LoginResponseMessage) {
                                LoginResponseMessage response = (LoginResponseMessage) msg;
                                if (response.isSuccess()) {
                                    //如果登录成功
                                    LOGIN.set(true);
                                }
                                else {
                                    System.out.println(response.getReason());
                                }
                                //登录后唤醒system in 线程
                                WAIT_FOR_LOGIN.countDown();
                            }
                            else if(msg instanceof ChatResponseMessage){
                                ChatResponseMessage response = (ChatResponseMessage) msg;
                                if(response.isSuccess()){
                                    String from = response.getFrom();
                                    String content = response.getContent();
                                    System.out.println(DateUtil.format(DateUtil.date(),"yyyy-MM-dd HH:mm:ss"));
                                    System.out.println(from+":");
                                    System.out.println(content);
                                }
                                else {
                                    System.out.println(response.getReason());
                                }
                            }
                            else if(msg instanceof GroupChatResponseMessage){
                                GroupChatResponseMessage response = (GroupChatResponseMessage) msg;
                                if(response.isSuccess()){
                                    String from = response.getFrom();
                                    String content = response.getContent();
                                    System.out.println(DateUtil.format(DateUtil.date(),"yyyy-MM-dd HH:mm:ss"));
                                    System.out.println(from+":");
                                    System.out.println(content);
                                }
                                else {
                                    System.out.println(response.getReason());
                                }
                            }
                            else if(msg instanceof GroupCreateResponseMessage){
                                GroupCreateResponseMessage response = (GroupCreateResponseMessage) msg;
                                System.out.println(response.getReason());
                            }
                            else if(msg instanceof GroupJoinResponseMessage){
                                GroupJoinResponseMessage response = (GroupJoinResponseMessage) msg;
                                System.out.println(response.getReason());
                            }
                            else if(msg instanceof GroupMembersResponseMessage){
                                GroupMembersResponseMessage response = (GroupMembersResponseMessage) msg;
                                if(response.isSuccess()){
                                    Set<String> members = response.getMembers();
                                    for (String member : members) {
                                        System.out.println(member);
                                    }
                                }
                                else {
                                    System.out.println(response.getReason());
                                }
                            }
                            else if(msg instanceof GroupQuitResponseMessage){
                                GroupQuitResponseMessage response = (GroupQuitResponseMessage) msg;
                                System.out.println(response.getReason());
                            }
                            else if(msg instanceof PongMessage){

                            }
                            else {
                                System.out.println("其他信息");
                            }
                        }
                    });
                }
            });
            Channel channel = bootstrap.connect("localhost", CommonConfig.getServerPort()).sync().channel();
            channel.closeFuture().sync();//等待channel关闭操作执行再往下运行
        } catch (Exception e) {
            log.error("client error", e);
        } finally {
            group.shutdownGracefully();//channel关闭之后就把eventLoop关了
        }
    }
}
